<template>
  <!-- 发货信息，用于导出代发货订单的excel交给快递公司 -->
  <el-dialog
    v-model="visible"
    :modal="false"
    :title="$t('retailProd.prodImport')"
    :close-on-click-modal="false"
    width="38%"
  >
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      class="upload-demo"
      :action="http.adornUrl('/shop/retailProd/importExcel')"
      :headers="{Authorization: cookie.get('b2cAuthorization'),locale:lang}"
      :limit="1"
      name="excelFile"
      :on-preview="handlePreview"
      :on-error="uploadFalse"
      :on-success="uploadSuccess"
      :auto-upload="false"
      :before-upload="beforeAvatarUpload"
    >
      <template #tip>
        <div class="el-upload__tip" />
      </template>
      <template #trigger>
        <div
          class="default-btn primary-btn"
        >
          {{ $t("retailProd.chooseFile") }}
        </div>
      </template>
      <div
        style="margin-left: 10px;"
        class="default-btn"
        @click="submitUpload"
      >
        {{ $t("retailProd.confirmImport") }}
      </div>
      <div
        style="margin-left: 10px;"
        class="default-btn"
        @click="downloadModel"
      >
        {{ $t("retailProd.DownloadTemplate") }}
      </div>
    </el-upload>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import http from '@/utils/http.js'
import cookie from 'vue-cookies'

const emit = defineEmits(['refreshUpload'])
const visible = ref(false)
const lang = localStorage.getItem('b2cLang') || 'zh_CN'
const fileList = ref([])

const uploadSuccess = (response) => {
  alert(response.data || $t('product.fileUploadFail'))
  fileList.value = []
  visible.value = false
  emit('refreshUpload')
}
const uploadFalse = (response) => {
  alert((isEn() ? 'File upload failed!' : '文件上传失败！') + response)
}
const init = () => {
  visible.value = true
}
// 上传前对文件的大小的判断
const beforeAvatarUpload = (file) => {
  const extension = file.name.split('.')[1] === 'xls'
  const extension2 = file.name.split('.')[1] === 'xlsx'
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!extension && !extension2) {
    alert(isEn() ? 'Upload template can only be in xls, xlsx format!' : '上传模板只能是 xls、xlsx格式!')
  }
  if (!isLt2M) {
    alert(isEn() ? 'Upload template size cannot exceed 10MB' : '上传模板大小不能超过 10MB!')
  }
  return extension || (extension2 && isLt2M)
}

const uploadRef = ref(null)
const submitUpload = () => {
  if (!fileList.value.length) {
    ElMessage.error($t('order.uploadInvoiceTip'))
    return
  }
  uploadRef.value?.submit()
}
const isEn = () => {
  return $t('language') === 'English'
}
const handlePreview = (file) => {
  if (file.response.status) {
    alert(isEn() ? 'This file import success' : '此文件导入成功')
  } else {
    alert(isEn() ? 'This file import failed' : '此文件导入失败')
  }
}
const downloadModel = () => {
  http({
    url: http.adornUrl('/shop/retailProd/importRetailProdModel'),
    method: 'get',
    responseType: 'blob' // 解决文件下载乱码问题
  }).then(({ data }) => {
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = isEn() ? 'SingleProductImportTemplate.xlsx' : '单品导入模板.xlsx'
    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  })
}

defineExpose({
  init
})
</script>
